/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-07
 * Time: 13:16
 */
public class MyBlockingQueue {
    private final Runnable[] array;
    private int head = 0;
    private int tail = 0;
    private int useSize = 0;

    public MyBlockingQueue(int capacity){
        this.array = new Runnable[capacity];
    }

    public synchronized void put(Runnable runnable) throws InterruptedException {
        while (isFull()){
            //阻塞
            this.wait();
        }
        array[tail] = runnable;
        tail++;
        if (tail >= array.length){
            tail = 0;
        }
        useSize++;
        this.notify();
    }

    public Runnable take() throws InterruptedException {
        Runnable runnable;
        synchronized (this) {
            while (useSize <= 0) {
                //阻塞
                this.wait();
            }
            runnable = array[head];
            head++;
            if (head >= array.length) {
                head = 0;
            }
            useSize--;
            this.notify();
        }
        return runnable;
    }

    public boolean isFull(){
        return useSize >= array.length;
    }
}
